package cn.lyq.card.ui.aboutus

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.View
import androidx.annotation.RequiresApi
import cn.lyq.card.BuildConfig
import cn.lyq.card.R
import cn.lyq.card.base.BaseDialogFg
import cn.lyq.card.data.model.AppInfo
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.king.app.updater.AppUpdater
import kotlinx.android.synthetic.main.dialog_new_version.*

class NewVersionFg(override val rootId: Int = R.layout.dialog_new_version) : BaseDialogFg() {

    private val code = 100
    private val mInfo by lazy {
        arguments?.getSerializable(KEY_INFO)
            ?.takeIf { it is AppInfo }
            ?.run { this as AppInfo }
    }

    companion object {
        private const val KEY_INFO = "INFO"

        fun newInstance(info: AppInfo): NewVersionFg {
            val args = Bundle()
            args.putSerializable(KEY_INFO, info)
            val fragment = NewVersionFg()
            fragment.arguments = args
            return fragment
        }
    }

    override fun initView(view: View) {
        super.initView(view)
        tvTip.text = mInfo?.updateMsg ?: getString(R.string.str_new_version_to_update_tip)
        tvCancel.visibility = getVisibility(mInfo?.isForce() ?: false)
        if (!BuildConfig.DEBUG) {
            isCancelable = false
        }
    }

    override fun initListener(view: View) {
        super.initListener(view)
        tvCancel.setClick {
            dismiss()
        }
        tvConfirm.setClick {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val canInstall = requireContext().packageManager.canRequestPackageInstalls()
                if (canInstall) {
                    downApk()
                } else {
                    startInstallPermissionSettingActivity()
                    ToastUtils.showLong(R.string.str_install_apk_permission_tip)
                }
            } else {
                downApk()
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private fun startInstallPermissionSettingActivity() {
        val packageURI: Uri = Uri.parse("package:${requireContext().packageName}")
        //注意这个是8.0新API
        val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
        startActivity(intent)
    }

    private fun downApk() {
        ToastUtils.showShort(R.string.str_downloading_tip)
        AppUpdater(requireContext(), mInfo?.downloadUrl ?: "").start()
    }

    override fun initObserver() {
        super.initObserver()
        PermissionUtils.permission(PermissionConstants.STORAGE)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: List<String>) {
                    LogUtils.d(permissionsGranted)
                }

                override fun onDenied(
                    permissionsDeniedForever: List<String>,
                    permissionsDenied: List<String>
                ) {
                    ToastUtils.showShort(R.string.str_permission_denied_to_install_apk_tip)
                    LogUtils.d(permissionsDeniedForever, permissionsDenied)
                }
            })
            .request()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == code) {
            if (resultCode == Activity.RESULT_OK) {
                downApk()
            } else {
                ToastUtils.showShort(R.string.str_refuse_permission_to_install)
            }
        }
    }
}